package com.wnhz.work.jy.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.solidfire.gson.Gson;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.wnhz.work.jy.BaseActivity;
import com.wnhz.work.jy.MyApplication;
import com.wnhz.work.jy.MyMain;
import com.wnhz.work.jy.R;
import com.wnhz.work.jy.bean.UserBean;
import com.wnhz.work.jy.utils.ConfigUtil;
import com.wnhz.work.jy.utils.MyUtils;
import com.wnhz.work.jy.utils.xutils3.MyCallBack;
import com.wnhz.work.jy.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import static com.wnhz.work.jy.MyMain.REQUEST_CODE;

public class BindinPhoneNumber extends BaseActivity implements View.OnClickListener {
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 666;
    private EditText et_phone, et_code, et_passWord, et_invitation, et_passWord_true;
    private String phoneNumber;
    private String password;
    private String password_two;
    private String code;
    private String invitationCode;
    private TextView tv_gain;
    private static final String TAG = "BindinPhoneNumber";

    private int time = 0;
    private TextView tv_agreement;

    private TextView title;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 55:
                    time--;
                    if (time == 0) {
                        tv_gain.setText("获取验证码");
                    } else {
                        tv_gain.setText("获取验证码" + time);
                        handler.sendEmptyMessageDelayed(55, 1000);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bindin_phone_number);
        initView();
        initTitle();
    }

    private void initView() {
        et_passWord_true = (EditText) findViewById(R.id.et_passWord_true);
        tv_gain = (TextView) findViewById(R.id.tv_gain);
        et_phone = (EditText) findViewById(R.id.et_phone);
        et_code = (EditText) findViewById(R.id.et_code);
        et_passWord = (EditText) findViewById(R.id.et_passWord);
        et_invitation = (EditText) findViewById(R.id.et_invitation);
        tv_agreement = (TextView) findViewById(R.id.tv_agreement);

        SpannableString text = new SpannableString("*注册/登录表示你已同意《嘉轶金服服务协议》");
        text.setSpan(new ForegroundColorSpan(0xffff3c3d), 12, 22, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_agreement.setText(text);

        findViewById(R.id.tv_sign).setOnClickListener(this);
        findViewById(R.id.tv_gain).setOnClickListener(this);
        findViewById(R.id.sys).setOnClickListener(this);
    }

    private void initTitle() {
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("绑定手机");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //注册
            case R.id.tv_sign:
                invitationCode = et_invitation.getText().toString();
                password = et_passWord.getText().toString();
                password_two = et_passWord_true.getText().toString();
                code = et_code.getText().toString();
                phoneNumber = et_phone.getText().toString();
                if (!MyUtils.isMobileNO(phoneNumber)) {
                    MyToast("请输入正确手机号");
                } else if (code == null || "".equals(code)) {
                    MyToast("请输入验证码");
                } else if (!phoneNumber.equals(oldphone)) {
                    MyToast("验证码与手机号不匹配");
                } else if (!code.equals(first_code)) {
                    MyToast("验证码错误");
                } else if (password.length() < 6) {
                    MyToast("密码不能少于6位");
                } else if (!password.equals(password_two)) {
                    MyToast("两次输入的密码不相同");
                } else {
                    sign();
                }

                break;

            case R.id.tv_gain:
                phoneNumber = et_phone.getText().toString();
                if (MyUtils.isMobileNO(phoneNumber)) {
                    if (time == 0) {
                        tv_gain.setClickable(false);
                        getCode(phoneNumber);
                    }
                }

                break;
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.sys:
                scanCode();
                break;
            default:
                break;
        }
    }

    public void scanCode() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    MY_PERMISSIONS_REQUEST_CALL_PHONE);
        } else {
            startActivityForResult(new Intent(this, CaptureActivity.class), REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startActivityForResult(new Intent(this, CaptureActivity.class), REQUEST_CODE);
            } else {
                MyToast("很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。");
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    private String oldphone;
    private String codetime;
    private String first_code;

    private void getCode(String phoneNumber) {
        Map<String, Object> map = new HashMap<>();
        map.put("phoneNumber", phoneNumber);

        showDialog();
        XUtil.Post(ConfigUtil.GETYZM, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.d(TAG, "onSuccess: " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("result");
                    if ("1".equals(re)) {
                        JSONObject jsonObject1 = jsonObject.optJSONObject("info");
                        oldphone = jsonObject1.optString("phone");
                        codetime = jsonObject1.optString("time");
                        first_code = jsonObject1.optString("code");
                        time = 60;
                        handler.sendEmptyMessage(55);
                    } else {
                        String info = jsonObject.optString("info");
                        MyToast(info);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }

            @Override
            public void onFinished() {
                super.onFinished();
                tv_gain.setClickable(true);
                closeDialog();
            }
        });

    }

    private void sign() {
        Map<String, Object> map = new HashMap<>();
        map.put("phoneNumber", phoneNumber);
        map.put("userName", MyApplication.getInstance().bean.getNickname());
        map.put("userImg", MyApplication.getInstance().bean.getHeadimgurl());
        map.put("openId", MyApplication.getInstance().bean.getOpenid());
        map.put("unionId", MyApplication.getInstance().bean.getUnionid());
        map.put("password", password);
        map.put("codeIstrue", code);
        map.put("oldphone", phoneNumber);
        map.put("codetime", codetime);
        if (invitationCode != null && !"".equals(invitationCode)) {
            map.put("invitationCode", invitationCode);
        }
        XUtil.Post(ConfigUtil.REGISTER_NORMALWX, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e(TAG, "onSuccess:sign " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("result");
                    if ("1".equals(re)) {

                        String results = jsonObject.optJSONObject("results").toString();
                        UserBean userBean = new UserBean();
                        userBean = new Gson().fromJson(results, UserBean.class);
                        MyApplication.getInstance().userBean = userBean;
                        startActivity(new Intent(BindinPhoneNumber.this, MyMain.class));
                    } else {
                        String msg = jsonObject.optString("msg");
                        if (msg != null || !"".equals(msg) || "null".equals(msg))
                            MyToast("绑定失败");
                        else
                            MyToast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    String s = "pid/";

                    if (result.indexOf(s) > 0) {
                        String pId = result.substring(result.indexOf(s) + s.length(), result.length());
                        Log.e(TAG, "onActivityResult: " + pId);
                        getInviteCode(pId);
                    }

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    MyToast("无效的二维码");
                }
            }
        }
    }

    private void getInviteCode(String pId) {
        Map<String, Object> map = new HashMap<>();
        map.put("pId", pId);
        showDialog();
        XUtil.Post(ConfigUtil.GETINVITECODE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e(TAG, "onSuccess: " + result);
                try {
                    String inviteCode = new JSONObject(result).optString("inviteCode");
                    et_invitation.setText(inviteCode);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }
        });
    }

}
